//
//  GongHaiShaiXuanView.m
//  JuBoCRM
//
//  Created by iMac on 2024/3/12.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "GongHaiShaiXuanView.h"
#import <UITableView+FDTemplateLayoutCell.h>
#import "HomePageSouSuoHeaderView.h"
#import "KeHuQuYuTableViewCell.h"
#import "BRAddressPickerView.h"
@implementation GongHaiShaiXuanView{
    NSMutableArray *dataSource;
    NSArray *origonArray;
    NSDictionary *paiXunDic;
    NSString *lastPoolId;
}
- (void)awakeFromNib{
    [super awakeFromNib];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    if (@available(iOS 15.0, *)) {
        self.mainTableView.sectionHeaderTopPadding = 0 ;
    } else {
        // Fallback on earlier versions
    }
    [_mainTableView registerNib:[UINib nibWithNibName:@"SearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"searchCell"];
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"KeHuQuYuTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeHuQuYuTableViewCell"];
    
    
    _bottomView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.1600].CGColor;
    _bottomView.layer.shadowOffset = CGSizeMake(0,0);
    _bottomView.layer.shadowOpacity = 1;
    _bottomView.layer.shadowRadius = 8;
    
    
    [self shiJianPaiXu:nil];
    
    [self getInfoFromServer];
    

}
- (void)setPoolId:(NSString *)poolId{
    _poolId = poolId;
    if(![lastPoolId isEqualToString:_poolId]){
        lastPoolId = _poolId;
        [self getInfoFromServer];
    }
}


- (void)getInfoFromServer{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:_poolId forKey:@"poolId"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmCustomerPool/queryPoolField" andParas:paraDic andShowHud:nil andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            origonArray = [info objectForKey:@"data"];
            [self zuZhuangShuJu];
        }
    }];
}

//组装数据
- (void)zuZhuangShuJu{
//    NSArray *array = @[@"客户阶段",@"地区定位",@"客户类型",@"纠纷类型",@"客户行业",@"员工与部门"];
    NSArray *array = @[@"level",@"address",@"fliedMjrdbe",@"fliedMtfnrf",@"industry",@"员工与部门"];
    dataSource = [NSMutableArray array];
    for (NSString *name in array) {
        NSDictionary *dataDic = [self huoQuShuJuDicWithName:name andArray:origonArray];
        [dataSource addObject:dataDic];
    }
    [_mainTableView reloadData];
}

//获取后台设置的数据
- (NSDictionary *)huoQuShuJuDicWithName:(NSString *)name andArray:(NSArray *)array{
    NSDictionary *tempDic = [NSDictionary dictionary];
    for (NSDictionary *dataDic in array) {
        if([GetHandleString(dataDic, @"fieldName") isEqualToString:name]){
            tempDic = dataDic;
            break;
        }
    }
    return tempDic;
}

- (void)setBuMenChangYuan:(NSString *)buMenChangYuan{
    _buMenChangYuan = buMenChangYuan;
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[5]];
    [dataDic setValue:buMenChangYuan forKey:@"value"];
    [dataSource replaceObjectAtIndex:5 withObject:dataDic];
    
    [UIView performWithoutAnimation:^{
        [_mainTableView reloadData];
    }];
}



//时间排序
- (IBAction)shiJianPaiXu:(UIButton *)sender {
//    NSArray *array = @[@{@"order":@"1"},@{@"order":@"2"},@{@"sortField":@"1"},@{@"sortField":@"2"}];
    NSArray *array = @[@{@"order":@"1",@"sortField":@"createTime"},@{@"order":@"2",@"sortField":@"createTime"},@{@"order":@"1",@"sortField":@"lastContent"},@{@"order":@"2",@"sortField":@"lastContent"}];
    for (NSInteger i =100; i < 104; i++) {
        UIButton *button = [self viewWithTag:i];
        if(sender.tag == i){
            [button setTitleColor:rgba(34, 99, 225, 1) forState:UIControlStateNormal];
            [button setBackgroundColor:rgba(242, 247, 255, 1)];
            button.layer.borderColor = [rgba(40, 120, 255, 1) CGColor];
            button.layer.borderWidth = 0.5f;
            paiXunDic = array[i-100];
        }else{
            [button setTitleColor:rgba(163, 168, 185, 1) forState:UIControlStateNormal];
            [button setBackgroundColor:rgba(247, 248, 250, 1)];
            button.layer.borderColor = [rgba(247, 248, 250, 1) CGColor];
            button.layer.borderWidth = 0.5f;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    HomePageSouSuoHeaderView *header = [HomePageSouSuoHeaderView view];
    header.titleLabel.text = @[@"客户阶段",@"地区定位",@"客户类型",@"纠纷类型",@"客户行业",@"员工与部门"][section];
    return header;
}

#pragma mark ========== tableview侧滑删除 S===================

#pragma mark ========== tableview侧滑删除 E===================

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
 
    return 42;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 6;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if(indexPath.section == 1 || indexPath.section == 5){
        NSDictionary *dataDic = dataSource[indexPath.section];
        KeHuQuYuTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeHuQuYuTableViewCell"];
        if(indexPath.section == 1){
            cell.leftSpace.constant = 36;
            cell.dingWeiImage.hidden = NO;
            cell.insertTextField.placeholder = @"请选择地区定位";
        }else{
            cell.leftSpace.constant = 16;
            cell.dingWeiImage.hidden = YES;
            cell.insertTextField.placeholder = @"请选择员工与部门";
        }
        cell.insertTextField.text = GetHandleString(dataDic, @"value");
        return cell;
    }
    
    SearchTableViewCell *searchCell = [tableView dequeueReusableCellWithIdentifier:@"searchCell"];
    searchCell.backgroundColor = [UIColor whiteColor];
    [self configCell:searchCell indexpath:indexPath];
    return searchCell;
}
- (void)configCell:(SearchTableViewCell *)cell indexpath:(NSIndexPath *)indexpath{
    
    NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexpath.section]];
    
    NSArray *array = [dataDic objectForKey:@"setting"];
    
    [cell.tagView removeAllTags];
    cell.tagView.backgroundColor = [UIColor whiteColor];
    cell.tagView.preferredMaxLayoutWidth = [UIScreen mainScreen].bounds.size.width;
    cell.tagView.padding = UIEdgeInsetsMake(6,16, 6, 16);
    cell.tagView.lineSpacing = 16;
    cell.tagView.interitemSpacing = 16;
    cell.tagView.singleLine = NO;
  
    cell.tagView.regularHeight = 28;

    if(indexpath.section == 0){
        cell.tagView.regularWidth = (ScreenWidth-16*3)/2.0;
    }else{
        cell.tagView.regularWidth = (ScreenWidth-16*4-1)/3.0;
    }
    
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SKTag *tag = [[SKTag alloc] initWithText:array[idx]];
        tag.font = [UIFont systemFontOfSize:14];
        tag.cornerRadius = 5;
        tag.enable = YES;
        
        
        if([GetHandleString(dataDic, @"value") isEqualToString:array[idx]]){
            tag.buttonStyle = 2;
        }else{
            tag.buttonStyle = 1;
        }
        
        
        tag.padding = UIEdgeInsetsMake(5, 12, 5, 12);
        [cell.tagView addTag:tag];
    }];
    
    cell.tagView.didTapTagAtIndex = ^(NSUInteger index){
        [dataDic setValue:array[index] forKey:@"value"];
        [dataSource replaceObjectAtIndex:indexpath.section withObject:dataDic];
        [UIView performWithoutAnimation:^{
            [_mainTableView reloadData];
        }];
    };
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1 || indexPath.section == 5){
        return 66;
    }
    
    return [tableView fd_heightForCellWithIdentifier:@"searchCell" configuration:^(id cell) {
        
        [self configCell:cell indexpath:indexPath];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.section == 1){
        BRAddressPickerView *addressPickerView = [[BRAddressPickerView alloc]init];
        addressPickerView.pickerMode = BRAddressPickerModeArea;
        addressPickerView.title = @"";
        addressPickerView.isAutoSelect = NO;
        addressPickerView.selectIndexs = self.addressSelectIndexs;
        addressPickerView.resultBlock = ^(BRProvinceModel *province, BRCityModel *city, BRAreaModel *area) {
            self.addressSelectIndexs = @[@(province.index), @(city.index), @(area.index)];
            self.addressSelectValues = @[province.name, city.name, area.name];
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionaryWithDictionary:dataSource[indexPath.section]];
            [dataDic setValue:[NSString stringWithFormat:@"%@,%@,%@",province.name,city.name,area.name] forKey:@"value"];
            [dataSource replaceObjectAtIndex:indexPath.section withObject:dataDic];

            [UIView performWithoutAnimation:^{
                [_mainTableView reloadData];
            }];
        };
        BRPickerStyle *customStyle = [[BRPickerStyle alloc]init];
        customStyle.pickerColor = [UIColor whiteColor];
        customStyle.selectRowTextColor = rgba(51, 51, 51, 1);
        customStyle.titleBarColor = [UIColor whiteColor];
        customStyle.titleTextColor = [UIColor whiteColor];
        customStyle.cancelTextColor = rgba(153, 153, 153, 1);
        customStyle.doneTextColor = rgba(40, 120, 255, 1);
        customStyle.titleBarHeight = 48;
        customStyle.titleTextFont = [UIFont systemFontOfSize:18];
        addressPickerView.pickerStyle = customStyle;
        customStyle.topCornerRadius = 10;
        customStyle.hiddenTitleLine = YES;
        customStyle.separatorColor = rgba(223, 229, 242, 1);
        customStyle.separatorHeight = 0.5;
        customStyle.rowHeight = 64;

        [addressPickerView show];
    }else if (indexPath.section == 5){
//        员工与部门
        if(_toSelectYuanGongBuMenBlock){
            _toSelectYuanGongBuMenBlock();
        }
    }
    
}


//重置
- (IBAction)chongZhi:(UIButton *)sender {
    [self zuZhuangShuJu];
    [self shiJianPaiXu:nil];
    _chengYuanArray = [NSArray array];
    _buMenArray = [NSArray array];
    self.addressSelectValues = [NSArray array];
     
}

//确定
- (IBAction)quDing:(UIButton *)sender {
    
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithDictionary:paiXunDic];
    
    
    NSMutableArray *array = [NSMutableArray array];
    
//    客户阶段
    NSDictionary *jieDuanDic = [self huoQuShuJuDicWithName:@"level" andArray:dataSource];
    if([GetHandleString(jieDuanDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"level" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(jieDuanDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    //    地区定位
    if(self.addressSelectValues.count > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"map_address" forKey:@"formType"];
        [dataDic setValue:@"address" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:self.addressSelectValues forKey:@"values"];
        [array addObject:dataDic];
    }
    //    客户类型
    NSDictionary *keHuLeiXingDic = [self huoQuShuJuDicWithName:@"fliedMjrdbe" andArray:dataSource];
    if([GetHandleString(keHuLeiXingDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"fliedMjrdbe" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(keHuLeiXingDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    纠纷类型
    NSDictionary *jieFenLeiXingDic = [self huoQuShuJuDicWithName:@"fliedMtfnrf" andArray:dataSource];
    if([GetHandleString(jieFenLeiXingDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"fliedMtfnrf" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(jieFenLeiXingDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    //客户行业
    NSDictionary *keHuHangYeDic = [self huoQuShuJuDicWithName:@"industry" andArray:dataSource];
    if([GetHandleString(keHuHangYeDic, @"value") length] > 0){
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"select" forKey:@"formType"];
        [dataDic setValue:@"industry" forKey:@"name"];
        [dataDic setValue:@"1" forKey:@"type"];
        [dataDic setValue:@[GetHandleString(keHuHangYeDic, @"value")] forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    部门
    if(_buMenArray.count > 0){
        NSMutableArray *temp = [NSMutableArray array];
        for (NSDictionary *tempD in _buMenArray) {
            [temp addObject:GetHandleString(tempD, @"deptId")];
        }
        
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"structure" forKey:@"formType"];
        [dataDic setValue:@"ownerDeptId" forKey:@"name"];
        [dataDic setValue:@"3" forKey:@"type"];
        [dataDic setValue:temp forKey:@"values"];
        [array addObject:dataDic];
    }
    
    //    负责人
    if(_chengYuanArray.count > 0){
        NSMutableArray *temp = [NSMutableArray array];
        for (NSDictionary *tempD in _chengYuanArray) {
            [temp addObject:GetHandleString(tempD, @"userId")];
        }
        
        NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
        [dataDic setValue:@"user" forKey:@"formType"];
        [dataDic setValue:@"ownerUserId" forKey:@"name"];
        [dataDic setValue:@"3" forKey:@"type"];
        [dataDic setValue:temp forKey:@"values"];
        [array addObject:dataDic];
    }
    
    [paraDic setValue:array forKey:@"searchList"];
    
    if(_manageResultBlock){
        _manageResultBlock(paraDic);
    }
    
}
- (void)setChengYuanArray:(NSArray *)chengYuanArray{
    _chengYuanArray = chengYuanArray;
}


- (void)setBuMenArray:(NSArray *)buMenArray{
    _buMenArray = buMenArray;
}





/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end



